package com.blank.site;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.blank.model.Company;

public class Cn716Site implements ISite {

	String defaulturl;

	public Cn716Site() {
		defaulturl = "http://www.cn716.com/company-8-121";
	}

	public void addListByUrl(String u) {

		try {
			InputStream is;
			is = Resources.getResourceAsStream("mybatis-config.xml");
			// 建立Session工厂
			SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
			// 获取Session
			SqlSession session = factory.openSession();
			Elements pages;
			String url = u;

			do {
				Document doc = Jsoup.connect(url).userAgent("Mozilla").get();
				Elements elements = doc.select(".sell_new li");
				pages = doc.select("a:contains(下一页)");
				url = pages.attr("abs:href").replaceAll("\\.\\./","");
				System.out.println(url);
				Iterator<Element> it = elements.iterator();

				while (it.hasNext()) {
         
					Element cp = it.next();
					Company company = new Company();
					company.setUrl(defaulturl+"/"+cp.select("a").first().attr("href"));
					company.setSource(defaulturl);
					company.setCompanyname(cp.select("a").first().html());
					session.insert(Company.class.getName() + ".add", company);
				}

			} while (pages.isEmpty() == false);
			session.commit();
			session.close();

		} catch (IOException e) {

			e.printStackTrace();
		}

	}

	public void run() {

		this.addListByUrl(defaulturl);

	}
}
